package com.rtsapp.server.platform.facebook;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rtsapp.server.app.AppConfig;
import com.rtsapp.server.logger.Logger;
import com.rtsapp.server.logger.LoggerFactory;
import com.rtsapp.server.platform.IPlatformLoginService;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;

/**
 * Created by admin on 17-9-18.
 */
public class AndroidFacebookPlatformLoginService implements IPlatformLoginService {

    private static final Logger LOGGER = LoggerFactory.getLogger( AndroidFacebookPlatformLoginService.class );

    private static final String FACEBOOK_VERIFY_URL = AppConfig.getInstance().getFaceBookUrl();

    private static final String FACEBOOK_SECRET = AppConfig.getInstance().getAndroidFacebookAppId() + "|" + AppConfig.getInstance().getAndroidFacebookAppSecret();

    @Override
    public String validateLoginToken(String token, String uid) {
        if ( token == null ) {
            return null;
        }

        LOGGER.info( "facebook 登录 sdk_token: " + token );

        String result = null;

        try {
            String url = String.format(FACEBOOK_VERIFY_URL, URLEncoder.encode(token,"utf-8"),URLEncoder.encode(FACEBOOK_SECRET,"utf-8"));
            result = httpGet(url);
            LOGGER.info("Facebook 登录:返回校验数据 "+ result);

            JSONObject jsonObject = JSON.parseObject(result);
            JSONObject dataObject = jsonObject.getJSONObject("data");

            result = dataObject.getString("user_id");
        } catch (Exception e) {
            LOGGER.error("Facebook 登录: 请求验证时返回错误",e);
            return null;
        }

        return result;
    }

    public static String httpGet(String url) throws IOException
    {
        if (null == url || url.isEmpty())
        {
            return "";
        }
        HttpGet httpGet = new HttpGet(url);
        System.out.println(url);
        // 设置超时时间为3s
        RequestConfig config = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).setAuthenticationEnabled(false).build();
        httpGet.setConfig(config);

        // 准备环境
        try (CloseableHttpClient http = HttpClients.createDefault(); CloseableHttpResponse response = http.execute(httpGet);)
        {
            // 返回内容
            HttpEntity entity = response.getEntity();
            // 主体数据
            InputStream in = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            // 读取
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
            {
                sb.append(line);
            }
            return sb.toString();
        }
    }
}
